import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:fsuper/fsuper.dart';

class BleScanPage extends StatefulWidget {
  @override
  _BleScanPageState createState() => _BleScanPageState();
}

class _BleScanPageState extends State<BleScanPage> {
  List<BluetoothDevice> devices = [];
  bool _isScan = true;
  StreamSubscription<BluetoothDiscoveryResult> _streamSubscription;

  @override
  void initState() {
    super.initState();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitUp,
    ]);
    _startScan();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 1.0,
        titleSpacing: 0.0,
        backgroundColor: Theme.of(context).canvasColor,
        title: Row(
          children: <Widget>[
            Text("扫描蓝牙", style: TextStyle(fontSize: 18)),
            SizedBox(width: 10),
            Offstage(
              offstage: !_isScan,
              child: SpinKitCircle(size: 24, color: Colors.grey),
            ),
          ],
        ),
        actions: <Widget>[
          FlatButton(
            onPressed: () => _restartDiscovery(),
            child: Text(
              _isScan ? "停止扫描" : "开始扫描",
              style: TextStyle(
                color: Theme.of(context).accentColor,
              ),
            ),
          )
        ],
      ),
      body: ListView.separated(
        itemBuilder: (context, index) {
          return _bleItemWidget(devices[index]);
        },
        separatorBuilder: (context, index) {
          return Container(height: 1, color: Color(0xffEEEEEE));
        },
        itemCount: devices.length,
      ),
    );
  }

  ///扫描到的蓝牙Item
  Widget _bleItemWidget(BluetoothDevice bleDevice) {
    return FSuper(
      height: 48,
      width: double.infinity,
      child1: Text(
        bleDevice.name ?? "未知",
        style: TextStyle(fontWeight: FontWeight.w800),
      ),
      child2: Text(
        bleDevice.address,
        style: TextStyle(color: Colors.grey),
      ),
      child1Alignment: Alignment.centerLeft,
      child2Alignment: Alignment.centerLeft,
      child1Margin: EdgeInsets.only(left: 20, bottom: 10),
      child2Margin: EdgeInsets.only(left: 20, top: 10),
      onClick: () {
        Navigator.pop(context, bleDevice);
      },
    );
  }

  @override
  void dispose() {
    super.dispose();
    _streamSubscription?.cancel();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeLeft,
    ]);
  }

  void _restartDiscovery() {
    if (_isScan) {
      return;
    }
    setState(() {
      devices.clear();
      _isScan = true;
    });
    _startScan();
  }

  ///开始扫描
  void _startScan() async {
    _streamSubscription =
        FlutterBluetoothSerial.instance.startDiscovery().listen((result) {
      if (devices.contains(result.device)) {
        return;
      }
      setState(() {
        devices.add(result.device);
      });
    });
    _streamSubscription.onDone(() {
      setState(() {
        _isScan = false;
      });
    });
  }
}
